package com.zcoj.service.impl;

import com.zcoj.pojo.Dto.ServerMetrics;
import com.zcoj.service.ServerMetricsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.stereotype.Service;

@Service
public class ServerMetricsServiceImpl implements ServerMetricsService {

    @Autowired
    private  MetricsEndpoint metricsEndpoint;

//    public ServerMetricsServiceImpl(MetricsEndpoint metricsEndpoint) {
//        this.metricsEndpoint = metricsEndpoint;
//    }

    @Override
    public ServerMetrics getServerMetrics() {
        ServerMetrics serverMetrics = new ServerMetrics();
        serverMetrics.setJvmMemoryMax(getMetricValue("jvm.memory.max"));
        serverMetrics.setJvmThreadsStates(getMetricValue("jvm.threads.states"));
        serverMetrics.setSystemLoadAverage1m(getMetricValue("system.load.average.1m"));
        serverMetrics.setJvmMemoryUsed(getMetricValue("jvm.memory.used"));
        serverMetrics.setSystemCpuCount((int)getMetricValue("system.cpu.count"));
        serverMetrics.setSystemCpuUsage(getMetricValue("system.cpu.usage"));
        serverMetrics.setTomcatSessionsCreated((int) getMetricValue("tomcat.sessions.created"));

        return serverMetrics;
    }

    private double getMetricValue(String metricName) {
        return metricsEndpoint.metric(metricName, null)
                .getMeasurements()
                .stream()
                .findFirst()
                .map(MetricsEndpoint.Sample::getValue)
                .orElse(0.0);
    }
}
